package com.sangfor.ssl.common;

import android.content.Context;
import android.os.Environment;
import android.os.FileObserver;
import android.text.TextUtils;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.common.IDeviceIdStorage;
import com.sangfor.ssl.service.utils.Common;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import org.json.JSONException;
import org.json.JSONObject;

/* loaded from: classes2.dex */
public class SharedDeviceIdStorage implements IDeviceIdStorage {
    private static final String CRYPTO_KEY = "8274/&(L:>KJHR%$ ><>N&^RVHJG^&INH&*NK<";
    private static final String LOCK_FILE_NAME = ".lock";
    private static final String MAP_FILE_NAME = "1958DD0946ABCD8ACB5E24D929F26CAB.db";
    private static final String SANGFOR_SHARED_DIR = ".sangfor";
    private static final String TAG = "SharedDeviceIdStorage";
    private JSONObject mCachedMap;
    private FileObserver mFileObserver;
    private IDeviceIdStorage.ContentChangedListener mListener;
    private FileLock mLock;
    private final File mLockFile;
    private FileOutputStream mLockOutputStream;
    private final File mMapFile;

    static /* synthetic */ File access$000() {
        return createSharedDir();
    }

    private SharedDeviceIdStorage(File file, File file2) {
        this.mMapFile = file;
        this.mLockFile = file2;
    }

    public static SharedDeviceIdStorage create(Context context) {
        File createSharedDir = createSharedDir();
        if (createSharedDir == null) {
            return null;
        }
        return new SharedDeviceIdStorage(new File(createSharedDir, MAP_FILE_NAME), new File(createSharedDir, LOCK_FILE_NAME));
    }

    @Override // com.sangfor.ssl.common.IDeviceIdStorage
    public void lockAndLoad() {
        if (this.mLock != null) {
            Log.warn(TAG, "locked before, reentrant");
            return;
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(this.mLockFile);
            this.mLockOutputStream = fileOutputStream;
            this.mLock = fileOutputStream.getChannel().lock();
        } catch (IOException e) {
            Log.error(TAG, "lock failed", e);
            closeQuietly(this.mLockOutputStream);
            this.mLockOutputStream = null;
        }
        this.mCachedMap = loadMap();
    }

    @Override // com.sangfor.ssl.common.IDeviceIdStorage
    public void saveAndRelease() {
        JSONObject jSONObject = this.mCachedMap;
        if (jSONObject != null) {
            saveFileContent(this.mMapFile, jSONObject.toString());
        }
        FileLock fileLock = this.mLock;
        try {
            if (fileLock != null) {
                try {
                    fileLock.release();
                } catch (IOException e) {
                    Log.error(TAG, "release lock failed", e);
                }
            }
            this.mLock = null;
            this.mLockOutputStream = null;
        } finally {
            closeQuietly(this.mLockOutputStream);
        }
    }

    @Override // com.sangfor.ssl.common.IDeviceIdStorage
    public String getId(IDeviceIdStorage.IdType idType) {
        checkNotNull(this.mCachedMap, "MUST call lockAndLoad first");
        return this.mCachedMap.optString(getKey(idType), null);
    }

    @Override // com.sangfor.ssl.common.IDeviceIdStorage
    public void putId(IDeviceIdStorage.IdType idType, String str) {
        checkNotNull(this.mCachedMap, "MUST call lockAndLoad first");
        try {
            this.mCachedMap.put(getKey(idType), str);
        } catch (Exception e) {
            Log.error(TAG, "put value to json failed", e);
        }
    }

    @Override // com.sangfor.ssl.common.IDeviceIdStorage
    public void registerContentChangedListener(IDeviceIdStorage.ContentChangedListener contentChangedListener) {
        FileObserver fileObserver = this.mFileObserver;
        if (fileObserver != null) {
            fileObserver.stopWatching();
        }
        this.mListener = contentChangedListener;
        FileObserver fileObserver2 = new FileObserver(this.mMapFile.getParent(), 3648) { // from class: com.sangfor.ssl.common.SharedDeviceIdStorage.1
            @Override // android.os.FileObserver
            public void onEvent(int i, String str) {
                Log.info(SharedDeviceIdStorage.TAG, "event=0x" + Integer.toHexString(i) + ", path=" + str);
                if ((i & 3648) == 0) {
                    return;
                }
                if (!(((i & 512) == 0 && (i & 64) == 0) ? false : true) || SharedDeviceIdStorage.MAP_FILE_NAME.equals(str)) {
                    if (SharedDeviceIdStorage.access$000() == null) {
                        Log.error(SharedDeviceIdStorage.TAG, "map file deleted but create shared dir failed");
                        return;
                    }
                    stopWatching();
                    if (SharedDeviceIdStorage.this.mListener != null) {
                        SharedDeviceIdStorage.this.mListener.onContentChanged(SharedDeviceIdStorage.this);
                    }
                    startWatching();
                }
            }
        };
        this.mFileObserver = fileObserver2;
        fileObserver2.startWatching();
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.sangfor.ssl.common.SharedDeviceIdStorage$2  reason: invalid class name */
    /* loaded from: classes2.dex */
    public static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$sangfor$ssl$common$IDeviceIdStorage$IdType;

        static {
            int[] iArr = new int[IDeviceIdStorage.IdType.values().length];
            $SwitchMap$com$sangfor$ssl$common$IDeviceIdStorage$IdType = iArr;
            try {
                iArr[IDeviceIdStorage.IdType.ANDROID_ID.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
        }
    }

    private static String getKey(IDeviceIdStorage.IdType idType) {
        if (AnonymousClass2.$SwitchMap$com$sangfor$ssl$common$IDeviceIdStorage$IdType[idType.ordinal()] == 1) {
            return "android_id";
        }
        throw new IllegalArgumentException("Unhandled id type: " + idType);
    }

    private JSONObject loadMap() {
        String readFileContent = readFileContent(this.mMapFile);
        Log.debug(TAG, "content=" + readFileContent);
        if (TextUtils.isEmpty(readFileContent)) {
            return new JSONObject();
        }
        try {
            return new JSONObject(readFileContent);
        } catch (JSONException e) {
            Log.error(TAG, "create json failed", e);
            return new JSONObject();
        }
    }

    /* JADX WARN: Not initialized variable reg: 2, insn: 0x005c: MOVE  (r0 I:??[OBJECT, ARRAY]) = (r2 I:??[OBJECT, ARRAY]), block:B:27:0x005c */
    private static String readFileContent(File file) {
        FileInputStream fileInputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        Closeable closeable;
        Closeable closeable2 = null;
        try {
            try {
                fileInputStream = new FileInputStream(file);
                try {
                    byteArrayOutputStream = new ByteArrayOutputStream(2048);
                } catch (IOException e) {
                    e = e;
                    byteArrayOutputStream = null;
                } catch (Throwable th) {
                    th = th;
                    closeQuietly(closeable2);
                    closeQuietly(fileInputStream);
                    throw th;
                }
            } catch (IOException e2) {
                e = e2;
                fileInputStream = null;
                byteArrayOutputStream = null;
            } catch (Throwable th2) {
                th = th2;
                fileInputStream = null;
            }
            try {
                byte[] bArr = new byte[4096];
                while (true) {
                    int read = fileInputStream.read(bArr);
                    if (read > 0) {
                        byteArrayOutputStream.write(bArr, 0, read);
                    } else {
                        String decrypt = Common.decrypt(byteArrayOutputStream.toByteArray(), CRYPTO_KEY);
                        closeQuietly(byteArrayOutputStream);
                        closeQuietly(fileInputStream);
                        return decrypt;
                    }
                }
            } catch (IOException e3) {
                e = e3;
                Log.error(TAG, "readFileContent failed: " + file.getAbsolutePath(), e);
                closeQuietly(byteArrayOutputStream);
                closeQuietly(fileInputStream);
                return null;
            }
        } catch (Throwable th3) {
            th = th3;
            closeable2 = closeable;
        }
    }

    private static void saveFileContent(File file, String str) {
        FileOutputStream fileOutputStream = null;
        try {
            try {
                FileOutputStream fileOutputStream2 = new FileOutputStream(file);
                try {
                    fileOutputStream2.write(Common.encrypt(str, CRYPTO_KEY));
                    fileOutputStream2.getFD().sync();
                    closeQuietly(fileOutputStream2);
                } catch (IOException e) {
                    e = e;
                    fileOutputStream = fileOutputStream2;
                    Log.error(TAG, "saveFileContent failed: " + file.getAbsolutePath(), e);
                    closeQuietly(fileOutputStream);
                } catch (Throwable th) {
                    th = th;
                    fileOutputStream = fileOutputStream2;
                    closeQuietly(fileOutputStream);
                    throw th;
                }
            } catch (IOException e2) {
                e = e2;
            }
        } catch (Throwable th2) {
            th = th2;
        }
    }

    private static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException unused) {
            }
        }
    }

    private static <T> T checkNotNull(T t, String str) {
        if (t != null) {
            return t;
        }
        throw new NullPointerException("" + str);
    }

    private static File createSharedDir() {
        if (!"mounted".equals(Environment.getExternalStorageState())) {
            Log.error(TAG, "sdcard not mounted");
            return null;
        }
        File file = new File(Environment.getExternalStorageDirectory(), SANGFOR_SHARED_DIR);
        if (file.isFile()) {
            file.delete();
        }
        if (file.mkdir() || file.isDirectory()) {
            return file;
        }
        Log.error(TAG, "create shared directory failed");
        return null;
    }
}
